package com.younion.action.manage;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;

import com.younion.business.ILoginService;
import com.younion.common.base.BaseAction;
import com.younion.common.constants.SysConstants;
import com.younion.common.exception.BaseException;
import com.younion.security.CaptchaUsernamePasswordToken;
import com.younion.vo.OperateLogVO;
import com.younion.vo.UserVO;

/**
 * @Title: LoginAction.java
 * @Package com.younion.action.manage
 * @author seagull
 * @date Sep 12, 2012 10:11:08 AM
 */

public class LoginAction extends BaseAction {

	private ILoginService loginService;

	private UserVO user;

	private String randomCode;

	public String loginPage() {
		return SUCCESS;
	}

	/**
	 * 登录
	 * 
	 * @return
	 */
	public String loginDo() {
		if (this.getSessionUser() != null)
			return SUCCESS;
		boolean accountExists = false;
		try {
			if (!request.getSession().getAttribute("random").equals(randomCode)) {
				tipMessage = "验证码输入错误，请重新输入!";
				return "loginFail";
			}

			accountExists = loginService.isEixsts(user.getAccount());
			if (!accountExists) {
				tipMessage = "用户名不存在，请核对后再登录!";
				return "loginFail";
			}
			UserVO loginUser = loginService.login(user);
			if (loginUser != null) {
				// Shiro 认证
				shiroAuthentication(loginUser);
				// 保存用户信息到session中
				setSessionUser(loginUser);
				//request.getSession().setMaxInactiveInterval(1);
				this.addLog(1, "登陆后台", "登陆", loginUser);
				return SUCCESS;
			} else {
				tipMessage = "密码错误，请重试!";
				return "loginFail";
			}
		} catch (BaseException e) {
			e.printStackTrace();
			tipMessage = "系统繁忙，请稍后再试!";
			return "loginFail";
		}
	}

	public String loginDailogPage() {
		return "loginDailogPage";
	}

	public String logout() {
		Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            subject.logout();
        }
		request.getSession().removeAttribute(SysConstants.SESSION_USER);
		
//		HttpSession session = request.getSession(false);
//        if (session != null) {
//            session.invalidate();
//        }
		return "logout";
	}

	public void setLoginService(ILoginService loginService) {
		this.loginService = loginService;
	}
	
	
	protected void shiroAuthentication(UserVO user){
		Subject currentUser = SecurityUtils.getSubject(); 
		if(!currentUser.isAuthenticated()){   
			CaptchaUsernamePasswordToken token = new CaptchaUsernamePasswordToken(user.getAccount(),user.getPassword(), true, request.getRemoteAddr(), randomCode );
			token.setUserId(user.getId());
			try {   
                currentUser.login(token); 
            }catch (UnknownAccountException ex) {
            	ex.printStackTrace();
    			//username provided was not found
    		} catch (IncorrectCredentialsException ex) {
    			//password provided did not match password found in database
    			//for the username provided
    			ex.printStackTrace();
    		}catch (Exception ex) {
    			ex.printStackTrace();
    			//Login NOT SUCCESSFUL - cause not known!
    		}  
		}
	}

	public void setUser(UserVO user) {
		this.user = user;
	}

	public UserVO getUser() {
		return user;
	}

	public String getRandomCode() {
		return randomCode;
	}

	public void setRandomCode(String randomCode) {
		this.randomCode = randomCode;
	}

}
